package cn.ysym.tcsy;

import android.Manifest;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.DealerDao;
import cn.ysym.dao.OfflineShippingDao;
import cn.ysym.dao.ProductDao;
import cn.ysym.dao.PromotionDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.model.Dealer;
import cn.ysym.model.Product;
import cn.ysym.model.Promotion;
import cn.ysym.model.Setting;
import cn.ysym.util.HttpUtil;

public class MainActivity extends AppCompatActivity {

    protected final int PERMS_REQUEST_CODE = 202;
    @BindView(R.id.export)
    Button export; //导出离线数据
    private SettingDao settingDao;
    private ProductDao productDao;
    private DealerDao dealerDao;
    private PromotionDao promotionDao;
    private ProgressBar progressBar;
//    private TextView tvLoginType;
    private Button bDownload;
//    private Button bUpload;
    private Button bStock;
    private Button bShipping;
    private Button bShippingMove;
    private Button bCancelStock;
    private Button bCodeReplace;
//    private SwitchLoginTask switchLoginTask;
    private DownloadTask downloadTask;
    private OfflineShippingDao offlineShippingDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("出入库管理");

        //6.0版本或以上需请求权限
        String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            requestPermissions(permissions, PERMS_REQUEST_CODE);
        }

        settingDao = new SettingDao(this);
        productDao = new ProductDao(this);
        dealerDao = new DealerDao(this);
        promotionDao = new PromotionDao(this);
        offlineShippingDao = new OfflineShippingDao(this);
        progressBar = (ProgressBar) findViewById(R.id.progressBarMain);
        doDownload();   //下载基础数据

//        Button bLoginSwitch = (Button) findViewById(R.id.bLoginSwitch);
//        bLoginSwitch.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                doLoginSwitch();
//            }
//        });

//        tvLoginType = (TextView) findViewById(R.id.tvLoginType);

        bDownload = (Button) findViewById(R.id.bDownload);
        bDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doDownload();
            }
        });

//        bUpload = (Button) findViewById(R.id.bUpload);
//        bUpload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(MainActivity.this, UploadDataActivity.class));
//            }
//        });

        bStock = (Button) findViewById(R.id.bStock);
        bStock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Setting loginType = settingDao.query("loginType");
                if ("1".equals(loginType.getSettingValue())) {
                    startActivity(new Intent(MainActivity.this, OnlineStockActivity.class));
                } else {
                    startActivity(new Intent(MainActivity.this, OfflineStockActivity.class));
                }
            }
        });

        bShipping = (Button) findViewById(R.id.bShipping);
        bShipping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Setting loginType = settingDao.query("loginType");
                if ("1".equals(loginType.getSettingValue())) {
                    startActivity(new Intent(MainActivity.this, OnlineShippingActivity.class));
                } else {
                    startActivity(new Intent(MainActivity.this, OfflineShippingActivity.class));
                }
            }
        });

        bShippingMove = (Button) findViewById(R.id.bShippingMove);
        bShippingMove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Setting loginType = settingDao.query("loginType");
                if ("1".equals(loginType.getSettingValue())) {
                    startActivity(new Intent(MainActivity.this, OnlineShippingMoveActivity.class));
                }
            }
        });

        bCancelStock = (Button) findViewById(R.id.bCancelStock);
        bCancelStock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Setting loginType = settingDao.query("loginType");
                if ("1".equals(loginType.getSettingValue())) {
                    startActivity(new Intent(MainActivity.this, OnlineCancelStockActivity.class));
                }
            }
        });

        bCodeReplace = (Button) findViewById(R.id.bCodeReplace);
        bCodeReplace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, CodeReplaceActivity.class));
            }
        });

        this.loginStatusShow();
    }

    private void loginStatusShow() {
        Setting loginType = settingDao.query("loginType");
        if ("1".equals(loginType.getSettingValue())) {
//            tvLoginType.setText("登录到服务器");
            bDownload.setVisibility(View.VISIBLE);
//            bUpload.setText("上传离线数据");
            bStock.setText("在线入库");
            bShipping.setText("在线出库");
            bShippingMove.setText("在线调货");
            bCancelStock.setText("在线退库");
            bCancelStock.setVisibility(View.VISIBLE);
            bCodeReplace.setVisibility(View.VISIBLE);
        } else {
//            tvLoginType.setText("登录到本地");
            bDownload.setVisibility(View.GONE);
//            bUpload.setText("查看离线数据");
            bStock.setText("离线入库");
            bShipping.setText("离线出库");
            bCancelStock.setVisibility(View.GONE);
            bCodeReplace.setVisibility(View.GONE);
        }
    }

//    private void doLoginSwitch() {
//        if (switchLoginTask != null) {
//            return;
//        }
//
//        progressBar.setVisibility(View.VISIBLE);
//        switchLoginTask = new SwitchLoginTask();
//        switchLoginTask.execute((Void) null);
//    }

    private void doDownload() {
        if (downloadTask != null) {
            return;
        }

        progressBar.setVisibility(View.VISIBLE);
        downloadTask = new DownloadTask();
        downloadTask.execute((Void) null);
    }

    public class DownloadTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");

                req.put("version", "2.2.161206");
                req.put("account", userName.getSettingValue());
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("downBaseData.sdo", req.toString());
                JSONObject retJson = new JSONObject(retStr);
                if (retJson.getInt("result") == 1) {
                    productDao.clearAll();
                    JSONArray products = retJson.getJSONArray("products");
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject product = products.getJSONObject(i);
                        if (product.has("productId")) {
                            Product model = new Product();
                            model.setProductId(product.getString("productId"));
                            model.setProductName(product.getString("productName"));
                            model.setProductNamePy(product.getString("productNamePy"));
                            productDao.insert(model);
                        }
                    }

                    dealerDao.clearAll();
                    JSONArray dealers = retJson.getJSONArray("dealers");
                    for (int i = 0; i < dealers.length(); i++) {
                        JSONObject dealer = dealers.getJSONObject(i);
                        if (dealer.has("dealerId")) {
                            Dealer model = new Dealer();
                            model.setDealerId(dealer.getString("dealerId"));
                            model.setDealerName(dealer.getString("dealerName"));
                            model.setDealerNamePy(dealer.getString("dealerNamePy"));
                            dealerDao.insert(model);
                        }
                    }

                    promotionDao.clearAll();
                    JSONArray promotions = retJson.getJSONArray("promotions");
                    for (int i = 0; i < promotions.length(); i++) {
                        JSONObject promotion = promotions.getJSONObject(i);
                        if (promotion.has("promotionId")) {
                            Promotion model = new Promotion();
                            model.setPromotionId(promotion.getString("promotionId"));
                            model.setPromotionName(promotion.getString("promotionName"));
                            model.setPromotionNamePy(promotion.getString("promotionNamePy"));
                            promotionDao.insert(model);
                        }
                    }

                    return true;
                }
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage());
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            downloadTask = null;
            progressBar.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "下载完成！",
                    Toast.LENGTH_SHORT).show();
        }
    }

//    public class SwitchLoginTask extends AsyncTask<Void, Void, Boolean> {
//
//        @Override
//        protected Boolean doInBackground(Void... params) {
//            Setting loginType = settingDao.query("loginType");
//            if ("0".equals(loginType.getSettingValue())) {
//                JSONObject req = new JSONObject();
//                try {
//                    Setting userName = settingDao.query("userName");
//                    Setting userPass = settingDao.query("userPass");
//                    req.put("account", userName.getSettingValue());
//                    req.put("passwd", userPass.getSettingValue());
//                    String retStr = HttpUtil.postJson("login.sdo", req.toString());
//                    JSONObject retJson = new JSONObject(retStr);
//                    if (retJson.getInt("result") == 1) {
//                        Setting sessionKey = settingDao.query("sessionKey");
//                        sessionKey.setSettingValue(retJson.getString("sessionKey"));
//                        settingDao.update(sessionKey);
//
//                        loginType.setSettingValue("1");
//                        settingDao.update(loginType);
//
//                        return true;
//                    }
//                } catch (Exception e) {
//                    Log.d("zqfw", e.getMessage());
//                }
//            } else {
//                loginType.setSettingType("loginType");
//                loginType.setSettingValue("0");
//                settingDao.update(loginType);
//
//                return true;
//            }
//
//            return false;
//        }
//
//        @Override
//        protected void onPostExecute(final Boolean success) {
//            switchLoginTask = null;
//            progressBar.setVisibility(View.GONE);
//
//            if (success) {
//                loginStatusShow();
//            }
//        }
//    }

}
